//统一管理 状态===多组件共享的数据


import type { dataTs } from "./storeTs"

//数据类型
type initStateTs = {
    datalist: Array<dataTs>
}

interface actionTs {
    type: string,
    payload: any
}

//管理的状态
let initState: initStateTs = {
    datalist: [
        { id: 1001, typeId: 1, title: '王明阳', ms: '王明阳描述', img: '/img/01.jpg', sub: true, collect: true },
        { id: 1002, typeId: 1, title: '庆余年2', ms: '庆余年2描述', img: '/img/02.jpg', sub: false, collect: false },
        { id: 1003, typeId: 1, title: '温柔又美好的友谊', ms: '温柔又美好的友谊描述', img: '/img/03.jpg', sub: false, collect: false },
        { id: 2001, typeId: 2, title: '后羿射日', ms: '后羿射日描述', img: '/img/04.jpg', sub: false, collect: false },
        { id: 2002, typeId: 2, title: '三体', ms: '三体描述', img: '/img/21.jpg', sub: false, collect: false },
        { id: 2003, typeId: 2, title: '哈利波特', ms: '哈利波特描述', img: '/img/22.jpg', sub: false, collect: false },
        { id: 3001, typeId: 3, title: '旧事理', ms: '旧事理描述', img: '/img/23.jpg', sub: false, collect: false },
        { id: 3002, typeId: 3, title: '一路繁花相送', ms: '一路繁花相送描述', img: '/img/31.jpg', sub: false, collect: false },
        { id: 3003, typeId: 3, title: '鲁滨逊漂流记', ms: '鲁滨逊漂流记描述', img: '/img/41.jpg', sub: false, collect: false },
    ]
}


//管理员函数：修改状态 返回新状态
/* 
oldState:原状态 == initState
action:对象 描述如何修改状态 {type:string唯一值,payload?:any传来的参数}
*/
function reducer(oldState: initStateTs, action: actionTs) {

    //不允许直接修改原状态
    let newlist = JSON.parse(JSON.stringify(oldState))

    //根据action描述如何修改状态
    let { type, payload } = action

    //收藏状态切换
    if (type == 'change_collect') {
        newlist.datalist.forEach((item: dataTs) => {
            if (item.id == payload)
                item.collect = !item.collect
        })
    }

    //订阅状态切换
    if (type == 'change_sub') {
        newlist.datalist.forEach((item: dataTs) => {
            if (item.id == payload)
                item.sub = !item.sub
        })
    }



    return newlist

}


//导出 管理的函数和管理的状态
export { reducer, initState }
